package com.example.gobang.api;

import com.example.gobang.game.*;
import com.example.gobang.model.User;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.util.ArrayList;
import java.util.List;

@Component
public class ChatApi extends TextWebSocketHandler {

    private ObjectMapper objectMapper = new ObjectMapper();

    private final List<ChatRoom> chatRooms = new ArrayList<>();

    @Autowired
    private RoomManger roomManger;

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        //根据user获取游戏房间的id,并以此为chatRoom的唯一标识
        User user = (User) session.getAttributes().get("user");
        String roomIdByUser = getRoomIdByUser(user);
        //先根据游戏房间的id获取chatRoom,如果没有创建,就依据游戏房间id新建,否则,加入已有的
        ChatRoom chatRoom = getChatRoomByRoomId(roomIdByUser);
        if (chatRoom != null){
            chatRoom.addPlayer(session);
        }else {
            chatRoom = new ChatRoom(roomIdByUser);
            chatRoom.addPlayer(session);
            chatRooms.add(chatRoom);
        }
        //返回给前端聊天室的id
        ChatResponse resp = new ChatResponse();
        resp.setOk(true);
        resp.setRoomId(chatRoom.getRoomId());
        session.sendMessage(new TextMessage(objectMapper.writeValueAsString(resp)));
    }

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        ChatRequest req = objectMapper.readValue(message.getPayload(), ChatRequest.class);
        //获取聊天室房间
        User user = (User) session.getAttributes().get("user");
        ChatRoom chatRoom = getChatRoomByRoomId(getRoomIdByUser(user));
        //发送消息 并 返回ThisUserName ThatUserName
        ChatResponse resp = new ChatResponse();
        if (chatRoom != null){
            //将消息发送给聊天室的两人
            chatRoom.broadcastMessage(user.getUsername(), req.getContent());
            //返回ThisUserName ThatUserName
            resp.setThisUserName(user.getUsername());
            List<WebSocketSession> players = chatRoom.getPlayers();
            User thatUser = null;
            for (WebSocketSession webSocketSession:players) {
                User tempUser = (User)webSocketSession.getAttributes().get("user");
                if (!resp.getThisUserName().equals(tempUser.getUsername())){
                    thatUser = tempUser;
                }
            }
            resp.setThatUserName(thatUser.getUsername());
        }else {
            resp.setOk(false);
            resp.setReason("网络异常");
        }
        session.sendMessage(new TextMessage(objectMapper.writeValueAsString(resp)));
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        System.out.println("聊天室关闭");
    }

    //获取游戏的房间id
    public String getRoomIdByUser(User user){
        Room room = roomManger.getRoomByUserId(user.getUserId());
        return room.getRoomId();
    }
    //获取聊天室房间
    public ChatRoom getChatRoomByRoomId(String roomId){
        for (ChatRoom chatRoom:chatRooms) {
            if (chatRoom.getRoomId().equals(roomId)){
                return chatRoom;
            }
        }
        return null;
    }
}
